<template>
  <div class="change-password-container">
    <el-card class="change-password-card">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Lock /></el-icon>
          <span>{{ isFirstLogin ? '首次登录 - 修改密码' : '修改密码' }}</span>
        </div>
        <p class="header-tip" v-if="isFirstLogin">
          <el-icon><InfoFilled /></el-icon>
          为了您的账号安全，首次登录需要修改密码
        </p>
      </template>

      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        class="password-form"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="form.newPassword"
            type="password"
            placeholder="请输入新密码（至少6位）"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
            clearable
            @keyup.enter="handleSubmit"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading" size="large" style="width: 100%">
            <el-icon><Check /></el-icon>
            确认修改
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Lock, InfoFilled, Check } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { changePassword } from '@/api/user'

const router = useRouter()
const userStore = useUserStore()
const formRef = ref<FormInstance>()
const loading = ref(false)

// 判断是否首次登录
const isFirstLogin = ref(false)

const form = reactive({
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入新密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度不能少于6位'))
  } else {
    if (form.confirmPassword !== '') {
      formRef.value?.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules: FormRules = {
  newPassword: [{ validator: validatePass, trigger: 'blur' }],
  confirmPassword: [{ validator: validatePass2, trigger: 'blur' }]
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await changePassword({
          oldPassword: undefined, // 首次登录不需要旧密码
          newPassword: form.newPassword
        })

        ElMessage.success('密码修改成功')

        // 更新用户信息
        if (userStore.userInfo) {
          userStore.userInfo.needChangePassword = 0
          localStorage.setItem('userInfo', JSON.stringify(userStore.userInfo))
        }

        // 跳转到信息完善页面或首页
        const roleCode = userStore.userInfo?.roleCode
        const infoCompleted = userStore.userInfo?.infoCompleted || 0

        if (roleCode === 'student' && infoCompleted === 0) {
          // 学生且未完善信息，跳转到完善信息页面（包含基本信息和家长绑定）
          ElMessage.info('请完善您的个人信息并绑定家长')
          setTimeout(() => {
            router.push('/complete-info')
          }, 1500)
        } else {
          // 已完善信息，跳转到首页
          setTimeout(() => {
            if (roleCode === 'student') {
              router.push('/student/dashboard')
            } else {
              router.push('/home')
            }
          }, 1500)
        }
      } catch (error: any) {
        ElMessage.error(error.response?.data?.msg || '密码修改失败')
      } finally {
        loading.value = false
      }
    }
  })
}

onMounted(() => {
  // 从store获取登录信息
  const userInfo = userStore.userInfo
  if (userInfo && userInfo.needChangePassword === 1) {
    isFirstLogin.value = true
  }
})
</script>

<style scoped lang="scss">
.change-password-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;

  .change-password-card {
    width: 100%;
    max-width: 500px;
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);

    :deep(.el-card__header) {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-bottom: none;
      padding: 24px;
    }

    .card-header {
      display: flex;
      align-items: center;
      font-size: 20px;
      font-weight: 600;

      .header-icon {
        font-size: 24px;
        margin-right: 12px;
      }
    }

    .header-tip {
      margin-top: 12px;
      margin-bottom: 0;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 8px;
      color: rgba(255, 255, 255, 0.9);

      .el-icon {
        font-size: 18px;
      }
    }

    :deep(.el-card__body) {
      padding: 32px;
    }

    .password-form {
      margin-top: 20px;

      :deep(.el-form-item__label) {
        font-weight: 500;
      }

      :deep(.el-input) {
        font-size: 15px;
      }

      :deep(.el-button) {
        height: 46px;
        font-size: 16px;
        font-weight: 500;
        border-radius: 8px;
        margin-top: 20px;
      }
    }
  }
}
</style>

